from http.server import BaseHTTPRequestHandler, HTTPServer

from Yfserver.Route import Route

routeClass = None


def useG():
    global routeClass
    if routeClass is None:
        routeClass = Route()
    return routeClass


class BaseServers(BaseHTTPRequestHandler):

    def do_GET(self):
        route = useG()
        if route.checkRoute(self.path):
            data = route.getRoute(self.path)
            self.sendcontent(200, data())
        else:
            self.senderrors("File Not Found", 404)

    def do_POST(self):
        route = useG()
        if route.checkRoute(self.path, "POST"):
            data = route.getRoute(self.path, "POST")
            self.sendcontent(200, data())
        else:
            self.senderrors("File Not Found", 404)

    def senderrors(self, message, codetype=404):
        self.send_error(codetype, message)
        self.end_headers()

    def sendcontent(self, statuscode, content="", contenttype="text/html"):
        self.send_response(statuscode)
        self.send_header('Content-type', contenttype)
        self.end_headers()

        self.wfile.write(bytes(content, 'utf-8'))


class RunService():
    http = {
        'servername': '0.0.0.0',
        'port': 8080
    }
    http_server = ''

    def bindport(self, port):
        self.http['port'] = port
        return self

    def bindserver(self, servername):
        self.http['servername'] = servername
        return self

    def run(self):
        self.http_server = HTTPServer((self.http['servername'], self.http['port']), BaseServers)
        print('running in http://' + self.http['servername'] + ':' + str(self.http['port']))
        self.http_server.serve_forever()
